package de.hochschuletrier.bachelor.antfarm.world;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.tiled.TiledMap;

import de.hochschuletrier.bachelor.antfarm.entity.Foodsource;
import de.hochschuletrier.bachelor.antfarm.entity.Nest;
import de.hochschuletrier.bachelor.antfarm.settings.Settings;

public class Map {
	private TiledMap map;
	private int width, height;
	private boolean[][] blockfield;

	public Map(int width, int height) {
		this();

		init();
	}

	public Map() {
		try {
			map = new TiledMap("./res/maps/dummy_map.tmx");
		}
		catch (SlickException e) {
			e.printStackTrace();
		}

		new Nest(25, 25, 8, 0);

		init();
	}

	private void init() {
		height = map.getHeight();
		width = map.getWidth();

		blockfield = new boolean[width][height];

		for (int x = 0; x < width; ++x) {
			for (int y = 0; y < height; ++y) {
				int id = map.getTileId(x, y, 0);
				String prop = map.getTileProperty(id, "blocked", "0");
				if (!prop.equals("0")) {
					blockfield[x][y] = true;
				}
			}
		}

		for (int i = 0; i < Settings.foodsourcesAtBegin; ++i) {
			createNewRandomFoodsource();
		}
	}

	public void createNewRandomFoodsource() {
		while (true) {
			int x = (int) (Math.random() * width);
			int y = (int) (Math.random() * height);

			if (!isTileBlocked(x, y)) {
				new Foodsource(x, y, 50);
				break;
			}
		}
	}

	public int getTileHeight(int x, int y) {
		int tileId = map.getTileId(x, y, 0);
		return new Integer(map.getTileProperty(tileId, "height", "0"));
	}

	public boolean isTileBlocked(int x, int y) {
		if (x < 0 || y < 0 || x >= width || y >= height) {
			throw new IllegalArgumentException();
		}
		return blockfield[x][y];
	}

	public void render(Graphics g, GameContainer gc) {
		map.render(0, 0);
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}
}
